﻿#include "stdafx.h"
#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include "modules.h"

// 这个文件定义一些 llvm 内部函数

using namespace llvm;

void make_printf(llvm::Module *module) {
	using namespace llvm;
	std::vector<Type *> params;
	params.push_back(Type::getInt8PtrTy(module->getContext(), 0));

	FunctionType *fType = FunctionType::get(
		Type::getInt32Ty(module->getContext()), params, true);

	 Constant *temp = module->getOrInsertFunction("printf", fType);
	if (!temp) {
		std::cerr << "printf function not in symbol table\n";
		exit(1);
	}

	// CLangModule::add("c", module);
}

using namespace std::experimental;
void enumLLFile(llvm::LLVMContext& context, const filesystem::path &full_path) {
	if (filesystem::exists(full_path)) {
		filesystem::directory_iterator item_begin(full_path);
		filesystem::directory_iterator item_end;
		for (; item_begin != item_end; item_begin++) {
			auto f = *item_begin;
			if (filesystem::is_directory(*item_begin)) {
				std::cout << f.path().string() << " \t[dir] " << std::endl;
				enumLLFile(context, f.path());
			}
			else {
				auto extension = f.path().extension();
				if (extension == ".ll")
					CLangModule::loadLLFile(f.path());
				else if (extension == ".si")	// c 语言对象定义
					CLangModule::loadSiFile(f.path());
				std::cout << f.path().string() << std::endl;
			}
		}
	}
}

void make_c_functions(llvm::Module *module) {
	enumLLFile(module->getContext(), "lib");
	make_printf(module);
}